import { login, getADs, getUserInfo, getGoodsList, getGoodDetails } from '@/api/mall'
export default {
  namespaced: true,
  state: {
    user: {
      id: 0,
      name: 'no one',
      balance: 0
    },
    notice: [
      {
        title: '123',
        content: 'ajn Agfa ADHFA',
        hasRead: true
      },
      {
        title: '42',
        content: 'fadjn Agfaaf ADHFA h',
        hasRead: true
      },
      {
        title: '6541',
        content: 'ajn Agfa ADHFA',
        hasRead: false
      },
      {
        title: '5fd',
        content: '噶人工湖 glak qert'
      },
      {
        title: '你跟他5fd',
        content: '啊儿通过 qert'
      },
      {
        title: 'grebe果然5fd',
        content: 'afag 儿亲耳后 钱 '
      }
    ],
    ad: {
      left: [],
      right: []
    },
    goods: {},
    cart: []
  },
  getters: {
    hasNoticeCount: (state, getters) => {
      return getters.noticeCount(false) > 0
    },
    noticeCount: (state) => (flag = false) => {
      if (flag) {
        return state.notice.length
      } else {
        return state.notice.filter((item) => {
          item.hasRead = false
        }).length
      }
    },
    goodsList: state => Object.values(state.goods),
    cartTotalPrice: state => {
      let total = 0
      for (let item of state.cart) {
        total += state.goods[item.id].price * item.num
      }
      return total
    },
    cartTotalPriceEx: (state, getters) => {
      return getters.cartTotalPrice.toFixed(2)
    }
  },
  mutations: {
    setADs (state, ads) {
      state.ad.left = ads.left
      state.ad.right = ads.right
    },
    setUser (state, userInfo) {
      state.user = userInfo
    },
    setGoods (state, goods) {
      state.goods = goods
    },
    setDetails (state, { id, details }) {
      if (id in state.goods) {
        Object.assign(state.goods[id], details)
        state.goods[id].solved = true
        console.log('committing', state.goods[id])
      } else {
        console.error('can not set details of unknow goods id:' + id)
      }
    },
    addCart (state, { id, num, details }) {
      console.log(id, num, details)
      state.cart.push({
        id,
        num,
        details
      })
    },
    updateCart (state, data) {
      console.log(data)
      let { idx, num } = data
      state.cart[idx].num += num
      if (state.cart[idx].num <= 0) {
        state.cart.splice(idx, 1)
      }
    },
    initCart (state) {
      try {
        state.cart = JSON.parse(localStorage.getItem('cart'))
      } catch (e) {
        console.error(e)
      }
    },
    removeCart (state) {
      state.cart = []
    },
    updateUserBalance (state, change) {
      state.user.balance += change
    }
  },
  actions: {
    initUser ({ commit, state }, { user, token }) {
      // return new Promise(resolve => {
      login(user, token).then(code => {
        getUserInfo(code).then(res => {
          commit('setUser', res.data.data)
          // resolve()
        })
      })
      // })
    },
    initAds (ctx, params) {
      getADs(params).then(res => {
        ctx.commit('setADs', res.data.data)
      }).catch(errors => {
        console.log(errors)
      })
    },
    initGoodsList ({ commit, state }, filter) {
      return new Promise((resolve, reject) => {
        getGoodsList(filter).then(res => {
          commit('setGoods', res.data.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    getGoodDetails ({ commit, state }, id) {
      return new Promise((resolve, reject) => {
        if (id in state.goods) {
          if (state.goods[id].solved) {
            resolve(state.goods[id])
          } else {
            getGoodDetails(id).then(res => {
              commit('setDetails', { id, details: res.data.data })
              console.log('after commit', state.goods[id])
              resolve(state.goods[id])
            })
          }
        } else {
          reject(new Error('404 NOT FOUND!'))
        }
      })
    },
    payCart ({ commit, state, getters }) {
      return new Promise((resolve, reject) => {
        if (getters.cartTotalPrice > state.user.balance) {
          reject(new Error('no enough balance'))
        } else {
          console.log(getters.cartTotalPrice)
          commit('updateUserBalance', -getters.cartTotalPrice)
          // commit('removeCart')
          state.cart = []
          resolve()
        }
      })
    }
  }
}
